package web_commands

import db.User
import org.hibernate.{ Session, SessionFactory }
import org.hibernate.cfg.Configuration
import db.Folder
import db.FolderManager
import client_updater.ClientsUpdater
import db.Client
import client_updater.FolderUpdate

/**
 * Created by IntelliJ IDEA.
 * User: Tamar
 * Date: 4/13/11
 * Time: 10:51 PM
 * To change this template use File | Settings | File Templates.
 */

class ShareFolder {
  
  def execute(userID : Long, folderID : Long, email : String) : Boolean = {
    val cfg = new Configuration()
    var sessionFactory : SessionFactory = null 
    var session : Session = null
    try{
	    sessionFactory = cfg.configure().buildSessionFactory()
	    session = sessionFactory.openSession()
	    //getting the user to share with
	    var query = session.createQuery("from User u where u.email = '"+email+"'")
	    val list = query.list.toArray
	    if(list.isEmpty) 
	      return false
	    else{
	      val userToShare = list.first.asInstanceOf[User]
	      //getting the folder to be shared
	      query = session.createQuery("from Folder f where f.folderID = "+folderID
	          							+" and f.userID = "+userID)
	      val folderToShare = query.list.toArray.first.asInstanceOf[Folder]
	      //getting the head folder of the user to share with
	      query = session.createQuery("from Folder f where f.userID = "
	    		  					+userToShare.getUserID+" and f.parentFolder = 0")
	      val headFolder = query.list.toArray.first.asInstanceOf[Folder]
	      val folder = new Folder
	      folder.setFolderID(folderID)
	      folder.setFolderName(folderToShare.getFolderName)
	      folder.setIsAdmin(0)
	      folder.setParentFolder(headFolder.getFolderID)
	      folder.setUserID(userToShare.getUserID)
	      val folderManager = new FolderManager(session)
	      folderManager.saveFolder(folder)
	      
	      //getting the clients to update
	      query = session.createQuery("from Client c where c.userID = "+userToShare.getUserID)
	      val clients = query.list.toArray
	      for( c <- clients ){
	        ClientsUpdater.addUpdate(c.asInstanceOf[Client].getClientID, 
	        				new FolderUpdate("New Folder", folder.getFolderName, 
	        				    folder.getParentFolder, folder.getFolderID))
	      }
	      
	      return true
	    }
    } catch { case (e : Exception) => e.printStackTrace } 
    return false
  }
}